import CreateModal from '@/components/InterfaceInfo/CreateModal';
import UpdateModal from "@/components/InterfaceInfo/UpdateModal";
import {
  addInterfaceInfoUsingPost,
  deleteInterfaceInfoUsingPost,
  listInterfaceInfoByPageUsingGet,
  offlineInterfaceInfoUsingPost,
  onlineInterfaceInfoUsingPost,
  updateInterfaceInfoUsingPost,
} from '@/services/api-backend/interfaceInfoController';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Divider, Drawer, message, Tooltip} from 'antd';
import {SortOrder} from 'antd/es/table/interface';
import React, {useRef, useState} from 'react';

import {useModel} from '@umijs/max';
import JsonView from '@uiw/react-json-view';

const JsonCell = ({json}) => {
  return (
    <JsonView value={json}/>
  );
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const {initialState, setInitialState} = useModel('@@initialState');
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在添加');
    try {
      await addInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      message.success('创建成功');

      handleModalOpen(false)


      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败' + error.message);
      return false;
    }
  };
  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfo) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改中');
    try {
      console.log(fields)
      await updateInterfaceInfoUsingPost({
        ...fields,
        id: currentRow.id
      });
      hide();
      message.success('修改成功');
      actionRef.current?.reload()
      handleUpdateModalOpen(false)
      return true;
    } catch (error) {
      hide();
      message.error('修改失败');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteInterfaceInfoUsingPost({
        id: record.id
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload()
      return true;
    } catch (error) {
      hide();
      message.error('删除失败.' + error.message);
      return false;
    }
  };
  /**
   *  Delete node
   * @zh-CN 发布
   *
   * @param selectedRows
   */
  const handleOnline = async (record: API.IdRequest) => {
    const hide = message.loading('正在发布');
    if (!record) return true;
    try {
      await onlineInterfaceInfoUsingPost({
        id: record.id
      });
      hide();
      message.success('发布成功');
      actionRef.current?.reload()
      return true;
    } catch (error) {
      hide();
      message.error('发布失败.' + error.message);
      return false;
    }
  };
  /**
   *  Delete node
   * @zh-CN 下线
   *
   * @param selectedRows
   */
  const handleOffline = async (record: API.IdRequest) => {
    const hide = message.loading('正在下线');
    if (!record) return true;
    try {
      await offlineInterfaceInfoUsingPost({
        id: record.id
      });
      hide();
      message.success('下线成功');
      actionRef.current?.reload()
      return true;
    } catch (error) {
      hide();
      message.error('下线失败.' + error.message);
      return false;
    }
  };
  // console.log(initialState)
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入接口名称',
        },
        ],
        required: true
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入描述',
        },],
        required: true
      },
      render: (text, record) => (
        <div className="ellipsis-text">
          <Tooltip placement="topLeft" title={record.description}>
            {record.description}
          </Tooltip>
        </div>
      ),
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'select',
      valueEnum: {
        option1: 'POST',
        option2: 'GET',
      },
      formItemProps: {
        rules: [{
          required: true,
          message: '请选择一个类型',
        },],
        required: true
      },

    },
    {
      title: '服务器地址',
      dataIndex: 'host',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入服务器地址',
        }],
        required: true
      }
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入接口地址',
        }],
        required: true
      }
    },

    {
      title: '请求参数',
      dataIndex: 'requestParams',
      // valueType: 'jsonCode',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入参数',
        }],
        required: true
      },
      hideInTable: true,
      hideInSearch: true
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入请求头',
        }],
        required: true
      },
      hideInTable: true,
      hideInSearch: true
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
      formItemProps: {
        rules: [{
          required: true,
          message: '请输入响应头',
        }],
        required: true
      },
      hideInTable: true,
      hideInSearch: true
    },
    {
      title: '数据详情', // 合并后的列标题
      key: 'dataDetails', // 你可以选择任意字段
      hideInSearch: true,
      filterDropdown: false,
      render: (text, record) => (
        <Tooltip
          color={'#CCFFFF'}
          title={
            <div style={{whiteSpace: 'pre-wrap', wordWrap: 'break-word', width: 150, padding: 10}}>
              {/* 将请求参数、请求头、响应头组合显示 */}
              <div><strong style={{color: "#000000"}}>请求参数:</strong> <JsonView collapsed={true}

                                                                                   value={JSON.parse(record.requestParams)}/>
              </div>
              <Divider/>
              <div><strong style={{color: "#000000"}}>请求头:</strong> <JsonView collapsed={true}
                                                                                 value={JSON.parse(record.requestHeader)}/>
              </div>
              <Divider/>
              <div><strong style={{color: "#000000"}}>响应头:</strong> <JsonView collapsed={true}
                                                                                 value={JSON.parse(record.responseHeader)}/>
              </div>
              {
                record.result && <>
                  <Divider/>
                  <div><strong style={{color: "#000000"}}>返回结果:</strong> <JsonView collapsed={true}
                                                                                       value={JSON.parse(record.result)}/>
                  </div>
                </>
              }
            </div>
          }
        >
          <Button>查看详情</Button>{/* 鼠标未移上时显示的文本 */}
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '是否付费',
      dataIndex: 'free',
      valueEnum: {
        0: {
          text: '免费',
          status: 'Success',
        },
        1: {
          text: '付费',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      sorter: true,
      render: (_, record) => [

        <Button
          key="config"
          type="link"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        record.status === 0 ? <Button
          key="online"
          type="link"
          onClick={() => {
            handleOnline(record);
          }}
        >
          发布
        </Button> : null,
        record.status === 1 ? <Button
          type={"text"}
          danger
          key="offline"
          onClick={() => {

            handleOffline(record);
          }}
        >
          下线
        </Button> : null,
        <Button
          type={"text"}
          danger
          key="remove"
          onClick={() => {

            handleRemove(record);
          }}
        >
          删除
        </Button>,

      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        scroll={{x: 'max-content', y: 'calc(100vh - 200px)'}}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined/> 上传接口
          </Button>,
        ]}
        request={async (
          params,
          sort: Record<string, SortOrder>,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          const res: any = await listInterfaceInfoByPageUsingGet({
            ...params,
            userId: initialState?.loginUser.id,
            sortField: "createTime",
            sortOrder: "descend"
          });
          if (res?.data) {
            return {
              data: res.data.records || [],
              success: true,
              total: res?.data.total || 0,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }

        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      <UpdateModal
        columns={columns}
        visible={updateModalOpen}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current?.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
      <CreateModal

        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(value) => {
          handleAdd(value);
        }}
        visible={createModalOpen}
      >
      </CreateModal>
    </PageContainer>
  );
};
export default TableList;
